<?php

namespace app\api\service\gifts;

use app\api\service\Basics;
use app\api\model\User as UserModel;
use app\api\model\gifts\GiftsOrderGoods as GiftsOrderGoodsModel;
use app\api\model\gifts\Order as OrderModel;
use app\api\model\dealer\Order as DealerOrderModel;
use app\common\enum\recharge\order\PayStatus as PayStatusEnum;
use app\api\model\gifts\UserGifts as UserGiftsModel;
use app\common\model\DistributionSetting as DistributionSettingModel;
use app\common\model\SingleOrder as SingleOrderModel;
use app\common\library\MysicLog;
use think\Db;
use app\common\model\dealer\User as DealerUserModel;

class PaySuccess extends Basics
{
    // 订单模型
    public $model;

    // 当前用户信息
    protected $user;

    // 当前订单快照
    protected $orderplan;

    private $mysicLog;

    /**
     * 构造函数
     * PaySuccess constructor.
     * @param $orderNo
     * @throws \think\exception\DbException
     */
    public function __construct($orderNo)
    {

        // 实例化订单模型
        $this->model = OrderModel::getPayDetail($orderNo);
        $this->wxappId = $this->model['wxapp_id'];
        // 获取用户信息
        $this->user = UserModel::detail($this->model['user_id']);
        // 获取订单快照
        $this->orderplan = GiftsOrderGoodsModel::detail(['order_id'=>$this->model['order_id']]);
        //log
        $this->mysicLog = MysicLog::instance();

    }


    /**
     * 订单支付成功业务处理
     * @param int $payType 支付类型
     * @param array $payData 支付回调数据
     * @return bool
     */
    public function onPaySuccess($payType, $payData)
    {   
        // 更新付款状态
        $status = $this->updatePayStatus($payType, $payData);
        return $status;
    }
    
     /**
     * 获取订单详情
     * @return OrderModel|null
     */
    public function getOrderInfo()
    {
        return $this->model;
    }


    /**
     * 更新付款状态
     * @param $payType
     * @param array $payData
     * @return bool
     */
    private function updatePayStatus($payType, $payData = [])
    {
        
         MysicLog::instance()->info("开始", '爆品礼订单回调..开始');
          //        return $this->model->transaction(function () use ($payType, $payData) {
            // 更新订单状态
            $this->model->save([
                'pay_status' => PayStatusEnum::SUCCESS,
                'pay_time' => time(),
                'transaction_id' => $payData['transaction_id'],
            ]);
            // 用户爆品礼领取记录表
            $gifts_log = [
                'superior_user_id'=>$this->model['superior_user_id'],
                'user_id' => $this->user['user_id'],
                'gifts_id' => $this->orderplan['gifts_id'],
                'gifts_title' => $this->orderplan['gifts_title'],
                'gifts_type' => $this->orderplan['gifts_type'],
                'image_id' => $this->orderplan['image_id'],
                'gifts_line_price' => $this->orderplan['gifts_line_price'],
                'gifts_price' => $this->orderplan['gifts_price'],
                'gifts_distribution_price' => $this->model['gifts_distribution_price'],
                'gifts_discription' => $this->orderplan['gifts_discription'],
                'gifts_content' => $this->orderplan['gifts_content'],
                'start_time' => $this->orderplan['start_time'],
                'end_time' => $this->orderplan['end_time'],
                'wxapp_id' => $this->orderplan['wxapp_id'],
                'linkman' => $this->orderplan['linkman'],
                'phone' => $this->orderplan['phone'],
                'address' => $this->orderplan['address'],
                'type' => 0,
                'order_id' => $this->model['order_id'],
            ];



            MysicLog::instance()->info("开始", '爆品礼订单回调..开始');

//            return $this->model->transaction(function () use ($payType, $payData) {

        try{
            // +----------------------------------------------------------------------
            // | 更新订单状态---gifts_order
            // +----------------------------------------------------------------------
            $this->model->save([
                'pay_status' => PayStatusEnum::SUCCESS,
                'pay_time' => time(),
                'transaction_id' => $payData['transaction_id'],//微信的交易号
            ]);

            $this->mysicLog->info("成功", '更新爆品礼订单状态成功');

            // +----------------------------------------------------------------------
            // | 用户爆品礼记录表加数据---user_gifts
            // +----------------------------------------------------------------------
            $gifts_log = [
                'superior_user_id'=>$this->model['superior_user_id'],//推荐人id
                'user_id' => $this->user['user_id'],//user_id
                'gifts_id' => $this->orderplan['gifts_id'],//爆品礼id
                'gifts_title' => $this->orderplan['gifts_title'],//爆品礼包名称
                'gifts_type' => $this->orderplan['gifts_type'],//爆品礼包类型(10免费 20不免费)
                'image_id' => $this->orderplan['image_id'],//爆品礼包图片
                'gifts_line_price' => $this->orderplan['gifts_line_price'],//划线价
                'gifts_price' => $this->orderplan['gifts_price'],//现价
                'gifts_distribution_price' => $this->model['gifts_distribution_price'],//爆品礼物分销价格
                'gifts_discription' => $this->orderplan['gifts_discription'],//爆品简介
                'gifts_content' => $this->orderplan['gifts_content'],//爆品详情
                'start_time' => $this->orderplan['start_time'],//固定时间-开始时间
                'end_time' => $this->orderplan['end_time'],//固定时间-结束时间
                'wxapp_id' => $this->orderplan['wxapp_id'],//小程序id
                'create_time'=>time(),//领取时间
                'is_delete'=>0,//是否删除 0 未删除 1已删除
                'write_status'=>10,//核销状态 10未核销  20 已核销
                'is_expire'=>0,//是否过期(0未过期 1已过期)
                'type' => 0,//0 购买 1领取
                'order_id' => $this->model['order_id'],//推荐人id
                'linkman' => $this->orderplan['linkman'],//联系人
                'phone' => $this->orderplan['phone'],//联系电话
                'address' => $this->orderplan['address'],//联系地址
            ];

            $this->mysicLog->info($gifts_log, '用户爆品礼领取记录表数据');
            $gifts_log_status = Db::name('user_gifts')->insertGetId($gifts_log);
            $this->mysicLog->info($gifts_log_status, '用户爆品礼领取记录表加数据结果');

            // +----------------------------------------------------------------------
            // | 爆品礼表更新库存以及已领取数量---gifts
            // +----------------------------------------------------------------------
            //Db::name('gifts')->where(['gifts_id'=>$gifts_log['gifts_id']])->setInc('receive_num');
            $this->mysicLog->info($gifts_log_status, '更新爆品礼的领取数量');
            $giftsInfo = Db::name('gifts')->where(['gifts_id'=>$gifts_log['gifts_id']])->find();
            if($giftsInfo['gifts_stock_num']>0){
                Db::name('gifts')->where(['gifts_id'=>$gifts_log['gifts_id']])->setDec('gifts_stock_num');
            }

            $this->mysicLog->info($gifts_log_status, '更新爆品礼的库存');

            // +----------------------------------------------------------------------
            // | 用户单条订单记录表加数据---single_order
            // +----------------------------------------------------------------------
            $orderData['amount']=$this->orderplan['gifts_price'];
            $orderData['pay_type']=60;
            $orderData['wxapp_id']=$this->orderplan['wxapp_id'];
            $orderData['user_id']=$this->user['user_id'];
            $this->singleOrder(['wxapp_id'=>$this->orderplan['wxapp_id'],'user_id'=>$this->user['user_id']],$orderData);
            $this->mysicLog->info("成功", '用户单条订单记录表加数据成功');

            // +----------------------------------------------------------------------
            // | 更新用户历史支付总金额---user
            // +----------------------------------------------------------------------
            Db::name('user')->where(['user_id'=>$this->user['user_id']])->setInc('pay_money',$this->model['pay_price']);
            $this->mysicLog->info("成功", '更新用户历史支付总金额成功');


            // +----------------------------------------------------------------------
            // | 更新用户为微股东---user
            // +----------------------------------------------------------------------
            Db::name('user')->where(['user_id'=>$this->user['user_id']])->update(['shareholder'=>1]);
            $this->mysicLog->info("成功", '更新用户为微股东成功');

            
            // +----------------------------------------------------------------------
            // | 发放分销佣金
            // +----------------------------------------------------------------------
            //联盟股东
            $this->mysicLog->info($this->model['gifts_distribution_price'], '爆品礼发放分销佣金金额');
            $this->mysicLog->info($this->model['superior_user_id'], '爆品礼发放分销佣金上级id');

            //发放分销佣金
            if($this->model['gifts_distribution_price']>0 && $this->model['superior_user_id']!=0){

                $this->grantMoney($gifts_log);

            }
            return true;
        } catch(\Exception $e) {
            $this->mysicLog->info(exceptionLogFormat($e), '爆品礼订单回调抛出异常');
        }

//            });


    }

    /**
     * 用户单条订单记录表
     * @param int $payType 支付类型
     * @param array $payData 支付回调数据
     * @return bool
     */

    public  function singleOrder($where,$data){
        //分销商表
        $flag = Db::name('single_order')->where($where)->find();
        if(!$flag){
            $single_data = [
                'amount'=>$data['amount'],
                'wxapp_id'=>$data['wxapp_id'],
                'pay_type'=>$data['pay_type'],
                'user_id'=>$data['user_id'],
                'create_time'=>time(),
                'update_time'=>time(),
            ];
            Db::name('single_order')->insertGetId($single_data);
        }else{
            if($flag['amount']<$data['amount']){
                $data['update_time'] = time();
                Db::name('single_order')->where($where)->update($data);
            }
        }
    }



    /**
     * 发放分销商佣金
     * @param $user_id
     * @param $money
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function grantMoney($gifts_log)
    {
        $this->mysicLog->setFilename('notify/giftsorder');
        // +----------------------------------------------------------------------
        // | dealer_order表加数据----分销商订单记录表
        // +----------------------------------------------------------------------
        $dealer_order = [
            'user_id' => $gifts_log['user_id'],//用户id
            'order_id' => $gifts_log['order_id'],//订单id
            'order_type' => 40,//购买爆品礼
            'order_price' => $gifts_log['gifts_price'],//订单总金额(不含运费)
            'first_user_id' => $gifts_log['superior_user_id'],//分销商用户id
            'second_user_id' => 0,//分销商用户id
            'third_user_id' => 0,//分销商用户id
            'first_money' => $gifts_log['gifts_distribution_price'],//分销佣金
            'second_money' => 0,//分销佣金
            'third_money' => 0,//分销佣金
            'is_settled' => 1,//是否已结算佣金(0未结算 1已结算)
            'settle_time' => time(),//结算时间
            'wxapp_id' => $gifts_log['wxapp_id'],//小程序id
            'create_time' => time(),//结算时间
            'update_time' => time(),//结算时间
            'dealer_case' =>  $this->model['dealer_case'],//分销方案
        ];
        $this->mysicLog->info($dealer_order, '分销订单表dealer_order表加数据');
        $dealer_order_id = Db::name('dealer_order')->insertGetId($dealer_order);
        $this->mysicLog->info($dealer_order_id, '分销订单表dealer_order表加数据结果');


        // +----------------------------------------------------------------------
        // | dealer_user表更新数据----分销商用户记录表
        // +----------------------------------------------------------------------
        $this->mysicLog->info($gifts_log['gifts_distribution_price'], '分销商用户记录表dealer_user，分销佣金');
        $this->mysicLog->info($gifts_log['superior_user_id'], '分销商用户记录表dealer_user，上级id');
        Db::name('dealer_user')->where(['user_id'=>$gifts_log['superior_user_id']])->setInc('money', $gifts_log['gifts_distribution_price']);


        // +----------------------------------------------------------------------
        // | dealer_capital表加数据----分销商资金明细表
        // +----------------------------------------------------------------------
        $capitalData = [
            'user_id'=>$gifts_log['superior_user_id'],
            'flow_type'=>40,
            'money'=>$gifts_log['gifts_distribution_price'],
            'wxapp_id'=>$gifts_log['wxapp_id'],
            'create_time'=>time(),
            'update_time'=>time(),
        ];

        $this->mysicLog->info($capitalData, '分销商资金明细表数据');
        $dealer_capital_id = Db::name('dealer_capital')->insertGetId($capitalData);

        $this->mysicLog->info($dealer_capital_id, '分销商资金明细表ID');

    }


    /**
     * 免费爆品礼
     * @param int $payType 支付类型
     * @param array $payData 支付回调数据
     * @return bool
     */
    public function paySuccess($giftsType, $payData=[])
    {
        // 更新付款状态
        $status = $this->upPayStatus($giftsType, $payData);
        return $status;
    }


    /**
     * 更新付款状态
     * @param $payType
     * @param array $payData
     * @return bool
     */
    private function upPayStatus($payType, $payData = [])
    {
        return $this->model->transaction(function () use ($payType, $payData) {
            // 更新订单状态
            $this->model->save([
                'pay_status' => PayStatusEnum::SUCCESS,
                'pay_time' => time(),
                'transaction_id' => "",
            ]);

            // +----------------------------------------------------------------------
            // | 爆品礼表更新库存以及已领取数量---gifts
            // +----------------------------------------------------------------------
            //Db::name('gifts')->where(['gifts_id'=>$this->orderplan['gifts_id']])->setInc('receive_num');

            $giftsInfo = Db::name('gifts')->where(['gifts_id'=>$this->orderplan['gifts_id']])->find();
            if($giftsInfo['gifts_stock_num']>0){
                Db::name('gifts')->where(['gifts_id'=>$this->orderplan['gifts_id']])->setDec('gifts_stock_num');
            }


            // +----------------------------------------------------------------------
            // | 用户爆品礼记录表加数据---user_gifts
            // +----------------------------------------------------------------------
            $gifts_log = [
                'superior_user_id'=>$this->model['superior_user_id'],//推荐人id
                'user_id' => $this->user['user_id'],//user_id
                'gifts_id' => $this->orderplan['gifts_id'],//爆品礼id
                'gifts_title' => $this->orderplan['gifts_title'],//爆品礼包名称
                'gifts_type' => $this->orderplan['gifts_type'],//爆品礼包类型(10免费 20不免费)
                'image_id' => $this->orderplan['image_id'],//爆品礼包图片
                'gifts_line_price' => $this->orderplan['gifts_line_price'],//划线价
                'gifts_price' => $this->orderplan['gifts_price'],//现价
                'gifts_distribution_price' => $this->model['gifts_distribution_price'],//爆品礼物分销价格
                'gifts_discription' => $this->orderplan['gifts_discription'],//爆品简介
                'gifts_content' => $this->orderplan['gifts_content'],//爆品详情
                'start_time' => $this->orderplan['start_time'],//固定时间-开始时间
                'end_time' => $this->orderplan['end_time'],//固定时间-结束时间
                'wxapp_id' => $this->orderplan['wxapp_id'],//小程序id
                'create_time'=>time(),//领取时间
                'is_delete'=>0,//是否删除 0 未删除 1已删除
                'write_status'=>10,//核销状态 10未核销  20 已核销
                'is_expire'=>0,//是否过期(0未过期 1已过期)
                'type' => 0,//0 购买 1领取
                'order_id' => $this->model['order_id'],//订单id
                'linkman' => $this->orderplan['linkman'],//联系人
                'phone' => $this->orderplan['phone'],//联系电话
                'address' => $this->orderplan['address'],//联系地址

            ];

            $gifts_log_status = Db::name('user_gifts')->insertGetId($gifts_log);
            return true;
        });
    }
}